'use client'

import React, { useState, useRef, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { toast } from 'sonner'
import { MessageCircle, Bot, MapPin, Calendar, Users, X } from 'lucide-react'
import { config } from '@/lib/config'

interface AIMessage {
  id: string
  type: 'user' | 'assistant'
  content: string
  timestamp: Date
  metadata?: {
    intent?: string
    entities?: Array<{ type: string; value: string }>
    suggestions?: string[]
  }
}

interface AIAssistantProps {
  hospitalId?: string
  onNavigateTo?: (location: { lng: number; lat: number; name: string }) => void
  onBookAppointment?: (department: string, doctor?: string) => void
  onGetInfo?: (type: 'department' | 'service' | 'facility', name: string) => void
  className?: string
}

export const AIAssistant: React.FC<AIAssistantProps> = ({
  hospitalId = 'default',
  onNavigateTo,
  onBookAppointment,
  onGetInfo,
  className = ''
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const [activeBot, setActiveBot] = useState<'guide' | 'activity'>('guide')
  const [messages, setMessages] = useState<AIMessage[]>([])
  const [inputValue, setInputValue] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const messagesEndRef = useRef<HTMLDivElement>(null)

  // 预设的AI回复模板
  const aiResponses = {
    guide: {
      greeting: '您好！我是医院智能导航助手，可以帮您:\n• 查找科室位置\n• 预约挂号\n• 了解医院服务\n• 导航路线\n\n请问需要什么帮助？',
      navigation: '我来为您导航到{location}，请跟随地图上的路线指示。',
      appointment: '正在为您查询{department}的号源信息...',
      info: '关于{topic}的信息如下...',
      fallback: '抱歉，我没有完全理解您的问题。您可以询问科室位置、预约挂号或医院服务等。'
    },
    activity: {
      greeting: '您好！我是医院商业活动助手，可以为您提供:\n• 餐饮推荐\n• 购物信息\n• 便民服务\n• 优惠活动\n\n有什么可以帮您的吗？',
      recommendation: '根据您的需求，推荐以下商铺...',
      promotion: '当前有以下优惠活动...',
      service: '以下是相关服务信息...',
      fallback: '抱歉，我没有理解您的需求。您可以询问餐饮、购物、服务等信息。'
    }
  }

  // 使用配置文件中的知识库数据
  const knowledgeBase = {
    departments: config.ai.departments,
    facilities: [
      { name: '药房', location: { lng: 120.1559, lat: 30.2749 }, floor: 'L1' },
      { name: '检验科', location: { lng: 120.1560, lat: 30.2750 }, floor: 'B1' },
      { name: '影像科', location: { lng: 120.1561, lat: 30.2751 }, floor: 'B1' },
      { name: '收费处', location: { lng: 120.1562, lat: 30.2752 }, floor: 'L1' }
    ],
    shops: [
      { name: '星巴克', type: '餐饮', location: { lng: 120.1563, lat: 30.2753 }, promotion: '新品上市，第二杯半价' },
      { name: '便利店', type: '零售', location: { lng: 120.1564, lat: 30.2754 }, promotion: '24小时营业' },
      { name: '花店', type: '服务', location: { lng: 120.1565, lat: 30.2755 }, promotion: '鲜花配送服务' }
    ]
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  // 初始化对话
  useEffect(() => {
    if (isOpen && messages.length === 0) {
      const welcomeMessage: AIMessage = {
        id: `msg_${Date.now()}`,
        type: 'assistant',
        content: aiResponses[activeBot].greeting,
        timestamp: new Date()
      }
      setMessages([welcomeMessage])
    }
  }, [isOpen, activeBot])

  // 意图识别和实体提取
  const analyzeMessage = (message: string) => {
    const normalizedMessage = message.toLowerCase()
    
    // 导航意图
    if (normalizedMessage.includes('在哪') || normalizedMessage.includes('怎么走') || normalizedMessage.includes('位置')) {
      const department = knowledgeBase.departments.find(d => 
        normalizedMessage.includes(d.name.toLowerCase())
      )
      const facility = knowledgeBase.facilities.find(f => 
        normalizedMessage.includes(f.name.toLowerCase())
      )
      
      return {
        intent: 'navigation',
        entity: department || facility,
        entityType: department ? 'department' : 'facility'
      }
    }
    
    // 预约意图
    if (normalizedMessage.includes('预约') || normalizedMessage.includes('挂号')) {
      const department = knowledgeBase.departments.find(d => 
        normalizedMessage.includes(d.name.toLowerCase())
      )
      
      return {
        intent: 'appointment',
        entity: department,
        entityType: 'department'
      }
    }
    
    // 购物推荐意图
    if (normalizedMessage.includes('吃') || normalizedMessage.includes('餐') || 
        normalizedMessage.includes('买') || normalizedMessage.includes('店')) {
      return {
        intent: 'shopping',
        entity: null,
        entityType: 'shop'
      }
    }
    
    // 活动查询意图
    if (normalizedMessage.includes('活动') || normalizedMessage.includes('优惠') || 
        normalizedMessage.includes('折扣')) {
      return {
        intent: 'promotion',
        entity: null,
        entityType: 'activity'
      }
    }
    
    return {
      intent: 'unknown',
      entity: null,
      entityType: null
    }
  }

  // 生成AI回复
  const generateResponse = (userMessage: string, analysis: any): AIMessage => {
    let content = ''
    let suggestions: string[] = []

    switch (analysis.intent) {
      case 'navigation':
        if (analysis.entity) {
          content = `${analysis.entity.name}位于${analysis.entity.floor}楼。我来为您导航。`
          suggestions = ['开始导航', '查看楼层信息', '预约挂号']
          
          // 触发导航
          if (onNavigateTo) {
            setTimeout(() => {
              onNavigateTo({
                lng: analysis.entity.location.lng,
                lat: analysis.entity.location.lat,
                name: analysis.entity.name
              })
            }, 1000)
          }
        } else {
          content = '请告诉我您要找的科室或设施名称，我来帮您导航。'
          suggestions = ['急诊科在哪', '药房位置', '收费处怎么走']
        }
        break
        
      case 'appointment':
        if (analysis.entity) {
          content = `正在为您查询${analysis.entity.name}的预约信息...\n\n今日号源:\n• 上午: 3个\n• 下午: 5个\n\n是否需要立即预约？`
          suggestions = ['立即预约', '查看医生排班', '了解科室信息']
          
          // 触发预约
          if (onBookAppointment) {
            setTimeout(() => {
              onBookAppointment(analysis.entity.name)
            }, 1000)
          }
        } else {
          content = '请告诉我您要预约哪个科室，我来帮您查询号源。'
          suggestions = ['内科预约', '外科挂号', '儿科预约']
        }
        break
        
      case 'shopping':
        if (activeBot === 'activity') {
          const shops = knowledgeBase.shops
          content = '为您推荐以下商铺:\n\n' + 
            shops.map(shop => `🏪 ${shop.name} (${shop.type})\n💡 ${shop.promotion}`).join('\n\n')
          suggestions = ['查看位置', '了解营业时间', '查看更多优惠']
        } else {
          content = '建议您咨询商业活动助手，可以为您提供更详细的购物信息。'
          suggestions = ['切换到活动助手', '查看餐饮推荐', '了解便民服务']
        }
        break
        
      case 'promotion':
        if (activeBot === 'activity') {
          content = '当前优惠活动:\n\n🎉 星巴克新品第二杯半价\n🛍️ 便利店24小时服务\n🌸 花店免费配送\n\n详情可前往相应店铺咨询。'
          suggestions = ['查看店铺位置', '了解活动详情', '获取优惠券']
        } else {
          content = '建议您咨询商业活动助手，可以获取最新的优惠活动信息。'
          suggestions = ['切换到活动助手']
        }
        break
        
      default:
        content = aiResponses[activeBot].fallback
        if (activeBot === 'guide') {
          suggestions = ['急诊科在哪', '预约内科', '药房位置']
        } else {
          suggestions = ['餐饮推荐', '优惠活动', '便民服务']
        }
    }

    return {
      id: `msg_${Date.now()}`,
      type: 'assistant',
      content,
      timestamp: new Date(),
      metadata: {
        intent: analysis.intent,
        suggestions
      }
    }
  }

  // 发送消息
  const sendMessage = async () => {
    if (!inputValue.trim()) return

    const userMessage: AIMessage = {
      id: `msg_${Date.now()}_user`,
      type: 'user',
      content: inputValue,
      timestamp: new Date()
    }

    setMessages(prev => [...prev, userMessage])
    setInputValue('')
    setIsLoading(true)

    // 模拟AI处理时间
    setTimeout(() => {
      const analysis = analyzeMessage(inputValue)
      const aiResponse = generateResponse(inputValue, analysis)
      setMessages(prev => [...prev, aiResponse])
      setIsLoading(false)
    }, config.ai.responseDelay)
  }

  // 处理建议点击
  const handleSuggestionClick = (suggestion: string) => {
    setInputValue(suggestion)
    setTimeout(() => sendMessage(), 100)
  }

  // 切换机器人类型
  const switchBot = (bot: 'guide' | 'activity') => {
    setActiveBot(bot)
    setMessages([]) // 清空对话
  }

  if (!isOpen) {
    return (
      <div className={`fixed bottom-4 right-4 z-50 ${className}`}>
        <Button
          onClick={() => setIsOpen(true)}
          size="lg"
          className="rounded-full w-14 h-14 shadow-lg"
        >
          <Bot className="w-6 h-6" />
        </Button>
      </div>
    )
  }

  return (
    <div className={`fixed bottom-4 right-4 w-96 h-[600px] bg-white rounded-lg shadow-2xl border z-50 flex flex-col ${className}`}>
      {/* 头部 */}
      <div className="flex items-center justify-between p-4 border-b">
        <div className="flex items-center space-x-2">
          <Bot className="w-5 h-5 text-blue-600" />
          <h3 className="font-semibold">
            {activeBot === 'guide' ? '智能导航助手' : '商业活动助手'}
          </h3>
        </div>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setIsOpen(false)}
        >
          <X className="w-4 h-4" />
        </Button>
      </div>

      {/* 机器人切换 */}
      <Tabs value={activeBot} onValueChange={(value) => switchBot(value as 'guide' | 'activity')} className="w-full">
        <TabsList className="grid w-full grid-cols-2 m-2">
          <TabsTrigger value="guide" className="text-xs">
            <MapPin className="w-3 h-3 mr-1" />
            导航助手
          </TabsTrigger>
          <TabsTrigger value="activity" className="text-xs">
            <Calendar className="w-3 h-3 mr-1" />
            活动助手
          </TabsTrigger>
        </TabsList>

        <TabsContent value={activeBot} className="flex-1 flex flex-col m-0">
          {/* 消息区域 */}
          <div className="flex-1 overflow-y-auto p-4 space-y-3">
            {messages.map((message) => (
              <div
                key={message.id}
                className={`flex ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}
              >
                <div
                  className={`max-w-[80%] p-3 rounded-lg ${
                    message.type === 'user'
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-100 text-gray-900'
                  }`}
                >
                  <p className="text-sm whitespace-pre-line">{message.content}</p>
                  
                  {/* 建议按钮 */}
                  {message.metadata?.suggestions && message.metadata.suggestions.length > 0 && (
                    <div className="mt-2 flex flex-wrap gap-1">
                      {message.metadata.suggestions.map((suggestion, index) => (
                        <Button
                          key={index}
                          variant="outline"
                          size="sm"
                          className="text-xs h-6"
                          onClick={() => handleSuggestionClick(suggestion)}
                        >
                          {suggestion}
                        </Button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            ))}
            
            {isLoading && (
              <div className="flex justify-start">
                <div className="bg-gray-100 p-3 rounded-lg">
                  <div className="flex space-x-1">
                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }}></div>
                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
                  </div>
                </div>
              </div>
            )}
            
            <div ref={messagesEndRef} />
          </div>

          {/* 输入区域 */}
          <div className="p-4 border-t">
            <div className="flex space-x-2">
              <Input
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                placeholder={activeBot === 'guide' ? '请问需要什么帮助？' : '想了解什么活动？'}
                onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
                disabled={isLoading}
              />
              <Button
                onClick={sendMessage}
                disabled={isLoading || !inputValue.trim()}
                size="sm"
              >
                发送
              </Button>
            </div>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  )
}

export default AIAssistant